import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_pink_app/composables/listbottom_loading.dart';
import 'package:flutter_pink_app/composables/status_appbar.dart';
import 'package:flutter_pink_app/serialized/recommend.dart';
import 'package:url_launcher/url_launcher.dart';
import '../composables/appbar_tabbar.dart';
import '../composables/homepage_swiper.dart';
import '../composables/popup_dialog.dart';
import '../composables/feed_list.dart';
import '../business/get_home_recommend.dart';
import '../style/color.dart';
import 'detail_page.dart';
import "../util.dart";

// 点击状态栏事件单例类
class ClickStatusbarAvatarNotification extends Notification {
  ClickStatusbarAvatarNotification._(); // 私有构造函数
  static ClickStatusbarAvatarNotification _instance; // 私有单例
  static ClickStatusbarAvatarNotification getInstance() {
    if (_instance == null) {
      _instance = ClickStatusbarAvatarNotification._();
    }
    return _instance;
  }
}

// Blibili首页组件
class BiliHomePage extends StatefulWidget {
  static int initalIndex = 0;

  @override
  _BiliHomePageState createState() => _BiliHomePageState();
}

class _BiliHomePageState extends State<BiliHomePage>
    with AutomaticKeepAliveClientMixin<BiliHomePage> {
  final int _reqAmount = 16; // 单次请求数量
  bool statusIconIsActive = false; // 是否点击状态栏图标
  List<CategoryInfo> _categoryList = <CategoryInfo>[]; // 目录列表
  List<BannerInfo> _bannerList = <BannerInfo>[]; // 首页轮播图用列表
  List<VideoInfo> _videoList = <VideoInfo>[]; // 首页影像数据列表
  int _reqPageIndex = 1; // 当前请求页面
  bool _isLoading = false; // 是否正在加载

  // 生命周期初始
  @override
  void initState() {
    super.initState();
    _initRequest();
  }

  @override
  void dispose() {
    super.deactivate(); // keepAlive
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;

  // 初始请求
  Future<void> _initRequest() async {
    final res = await getHomeRecommend(
        amount: _reqAmount, pageIndex: _reqPageIndex); // 远程请求首页数据
    if (res == null) {
      print("首页模块数据请求失败");
      Timer(Duration(seconds: 5), _initRequest); // 请求失败5秒后发起轮循
      return; // 如果请求失败则直接返回
    }
    _updatePageIndex();
    // 请求到数据后如果当前页面仍存在即刷新原始数据
    if (mounted) {
      setState(() {
        _categoryList = res.categoryList;
        _bannerList = res.bannerList;
        _videoList = res.videoList;
      });
    }
  }

  // 更新请求信息数量
  void _updatePageIndex() {
    _reqPageIndex++;
  }

  // 设置是否正在加载中
  void setIsLoading(bool value) {
    setState(() {
      _isLoading = value;
    });
  }

  // 请求更多影像数据，传给子级
  Future<void> _loadMoreVideo({bool isTopRefresh = false}) async {
    print('loadMoreVideo at home_page');
    setIsLoading(true);
    final res = await getHomeRecommend(
        amount: _reqAmount, pageIndex: _reqPageIndex); // 请求数据
    setIsLoading(false);
    // 排除非空情况
    if (res == null) {
      return;
    }
    // 请求到数据后如果当前页面仍存在且仍有数据即刷新原始数据
    final vl = res.videoList ?? [];
    if (mounted && vl.length > 0) {
      setState(() {
        if (isTopRefresh == true) {
          _videoList.insertAll(0, vl.toList());
        } else {
          _videoList.addAll(vl.toList());
        }
      });
      // 更新数据
      _updatePageIndex();
    }
  }

  // 构建头部栏
  Widget _buildAppbar(BuildContext ctx) {
    return PreferredSize(
      preferredSize: Size(double.maxFinite, 102), // 高度为102px
      child: Column(
        children: [
          StatusAppbar(
            onAvatarTap: () => ClickStatusbarAvatarNotification.getInstance()
                .dispatch(ctx), // 派发自定义事件
            iconColor: statusIconIsActive ? mainThemeColor : grayTextColor,
            onSearchbarTap: () =>
                popupDialog(ctx, content: '搜索模块还没上线ing', buttonText: '没办法~'),
            onIconTap: () =>
                setState(() => statusIconIsActive = !statusIconIsActive),
          ),
          buildAppbarTabbar(
              strList: _categoryList
                  .map((info) => filterSafeText(info.name))
                  .toList())
        ],
      ),
    );
  }

  // 跳转URL方法
  Future<void> _launchUrl(String url) async {
    return await canLaunch(url)
        ? await launch(url)
        : throw 'Could not launch $url';
  }

  // 构建主站页面
  Widget _buildIndexPage() {
    return RefreshIndicator(
      onRefresh: () => _loadMoreVideo(isTopRefresh: true),
      color: mainThemeColor,
      child: Stack(
        children: [
          Column(
            // 主站页面按照一比二来平分布局
            children: <Widget>[
              Expanded(
                  child: HomePageSwiper(
                    _bannerList.map((e) => e.cover).toList(),
                    onTapped: (int index) => _launchUrl(_bannerList[index].url),
                    padding: EdgeInsets.all(6),
                    setPaginationShadow: true,
                    floatTextList: _bannerList.map((e) => e.title).toList(),
                  ),
                  flex: 1),
              Expanded(
                  child:
                      Feed2DList(_videoList, refreshCallback: _loadMoreVideo),
                  flex: 2),
            ],
          ),
          Positioned(
            bottom: 0,
            right: 0,
            left: 0,
            child: ListBottomLoading(
              loadingText: "~ 正在努力加载中 QAQ ~",
              isOff: !_isLoading,
            ),
          ),
        ],
      ),
    );
  }

  // 构建tabView页面
  List<Widget> _buildTabViewPages(List<CategoryInfo> list) {
    final res = <Widget>[];
    for (int i = 0; i < list.length; i++) {
      if (i == 0) {
        // 第一项返回主站页面
        res.add(_buildIndexPage());
        continue;
      }
      res.add(DetailPage(list[i]));
    }
    return res;
  }

  @override
  Widget build(BuildContext defaultTabControllerCtx) {
    super.build(defaultTabControllerCtx); // keepAlive
    return DefaultTabController(
      initialIndex: BiliHomePage.initalIndex,
      length: _categoryList.length,
      child: Scaffold(
        appBar: _buildAppbar(defaultTabControllerCtx),
        body: TabBarView(
          physics: BouncingScrollPhysics(),
          children: _buildTabViewPages(_categoryList),
        ),
      ),
    );
  }
}
